﻿Public Class CToolFileIni
    Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer
    ''' <summary>
    ''' 读取ini文件的某一值
    ''' </summary>
    ''' <param name="groupName"></param>
    ''' <param name="keyName"></param>
    ''' <param name="fileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ReadKey(groupName As String, keyName As String, Optional fileName As String = "") As String
        Dim temp As String
        Dim m As Integer
        If Len(fileName) <= 0 Then fileName = System.Environment.CurrentDirectory & "\system.ini"
        If My.Computer.FileSystem.FileExists(fileName) Then
            temp = New String(" ", 2048)
            m = GetPrivateProfileString(groupName, keyName, "", temp, Len(temp), fileName)
            Return Mid(temp, 1, m)
        Else
            Return ""
        End If
    End Function

    ''' <summary>
    ''' 填写ini文件的某一值
    ''' </summary>
    ''' <param name="groupName"></param>
    ''' <param name="keyName"></param>
    ''' <param name="value"></param>
    ''' <param name="fileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function WriteKey(groupName As String, keyName As String, value As String, Optional fileName As String = "") As Boolean
        Try
            If Len(fileName) <= 0 Then
                fileName = System.Environment.CurrentDirectory & "\system.ini"
            End If
            WritePrivateProfileString(groupName, keyName, value, fileName)
            Return True
        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try
    End Function
End Class
